package com.example.demo.config;

import com.example.demo.annotation.DistributedLockAdvice;
import com.example.demo.annotation.IDistributedLock;
import com.example.demo.annotation.RedisDistributedLock;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.integration.support.locks.LockRegistry;

/**
 * @Auther Created by l.wang on 2019/1/15.
 */
@Configuration
public class DistributedLockConfigurations {
    private static final String OVERALL_LOCK = "OVERALL_LOCK";

    @Bean
    @ConditionalOnMissingBean(LockRegistry.class)
    public IDistributedLock distributedLock(ApplicationContext applicationContext) {
        RedisConnectionFactory redisConnectionFactory = applicationContext.getBean(RedisConnectionFactory.class);
        RedisLockRegistry registry = new RedisLockRegistry(redisConnectionFactory, OVERALL_LOCK);
        RedisDistributedLock redisDLock = new RedisDistributedLock(registry);
        return redisDLock;
    }

    @Bean
    @ConditionalOnBean(IDistributedLock.class)
    public DistributedLockAdvice distributedLockAdvice(IDistributedLock distributedLock) {
        return new DistributedLockAdvice(distributedLock);
    }

}
